#coding:utf-8
import base64
import time
import subprocess
import requests
import sys


__author__ = 'yangxianming'
"""
request_header 中的biz_content进jar包前为原始业务数据json格式，去jar包后取出biz_content做加密并生成sign
"""

class OpenPlatformHttp:
    path = sys.path[0] + "/common/ebuyOpenPlatformUtil/"
    #如果在case中运行激活这个
    path = "../common/ebuyOpenPlatformUtil/"
    #如果在main或者remotemain中运行激活这个
    # path = "common/ebuyOpenPlatformUtil/"
    publicKeyFileName = "test_public_key.txt"
    privateKeyFileName = "test_rsa_private_key.pkcs8"
    tempFileName = "Temp"
    # app_id = "102410038"
    app_id = "welfarepoint12345678901234567890"   #福员外
    #app_id = "9d1204f8211a424aa881ed838e3895b4"   #平安一账通
    version = "20171227"
    appPrivateKey = ""
    publicKey = ""
    sign = ""

    def send_http(self, app_host, action, dict_param={}):
        t = str(int(time.time() * 1000))
        request_header = \
            {"app_id": self.app_id,
             "action": action,
             "timestamp": t,
             "version": self.version,
             "biz_content": str(dict_param)}
        request_header_str = str(request_header).replace(" ", "")
        # print("request_header:" + request_header_str)
        #需要加密数据覆盖入文件
        #从零时文件读取加密数据
        with open(self.path + self.tempFileName, 'w',encoding="utf-8") as f:
            f.write(request_header_str)

        #加密参数 getSign [request_header_str] [appPrivateKey] [publicKey]
        command = "java -jar " + self.path + "EbuyOpenPlatformUtil.jar getSign " + self.privateKeyFileName + " " + self.publicKeyFileName

        # print("command:" + command + "\n")
        p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        l = str(p.stdout.read())
        # print("pydebug: " + l)

        #从零时文件读取加密数据
        with open(self.path + self.tempFileName, 'r',encoding="utf-8") as f:
            self.sign = f.read()
        # print("sign return:" + sign)
        headers = {"Content-Type": "application/json", "Content-Encoding": "UTF-8"}
        r = requests.post(app_host, data=str(self.sign), headers=headers)
        #返回
        rjson = r.json()
        # print("这个是接口返回的全部参数", rjson)
        if "biz_content" in rjson:
            # print("biz_content: " + rjson["biz_content"])
            base64_decrypt = base64.b64decode(rjson["biz_content"].encode('utf-8'))
            command = "java -jar EbuyOpenPlatformUtil.jar getResContent " + rjson["biz_content"]
            print(command)
            p1 = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            l = str(p1.stdout.read())
            r = l[2:-1]
            print(r)
            return str(base64_decrypt,'utf-8')
        return rjson
